package haproxy

import (
	"haproxy-mgr-go/models/global_config"
	"haproxy-mgr-go/models"
	"fmt"
	"haproxy-mgr-go/models/maps"
	"strings"
	"haproxy-mgr-go/models/targets"
	"os"
	"io"
	"github.com/astaxie/beego"
	"haproxy-mgr-go/utils"
)

var Cfg = beego.AppConfig
var haConfPath = Cfg.String("ha_conf_path")
var haExcutor = Cfg.String("ha_exec_path")

func InitHAConf() {
	var f *os.File
	var err1 error
	/***************************** 第一种方式: 使用 io.WriteString 写入文件 ***********************************************/
	if utils.CheckFileIsExist(haConfPath) { //如果文件存在
		os.Remove(haConfPath)
	}

	f, err1 = os.Create(haConfPath) //创建文件

	utils.Check(err1)
	_, err1 = io.WriteString(f, getAllConf()) //写入文件(字符串)
	utils.Check(err1)
}



func getAllConf() string {
	globalConfigs := global_config.FindAll()
	var globalConfig models.GlobalConfig
	if len(globalConfigs) == 0 {
		globalConfig = global_config.InitConfigs()
	}else {
		globalConfig = globalConfigs[0]
	}

	confStr := baseConfig(globalConfig)

	mapList := maps.FindAll()

	for _, m := range mapList {
		confStr += fmt.Sprintf(`
frontend %s
	mode %s
	bind 0.0.0.0:%s
	default_backend %s
backend %s
	balance roundrobin`,
		m.MapName,
		m.MapType,
		m.MapPort,
		m.MapName,
		m.MapName)

		idstrs := strings.Split(m.MapTargetId, ",")
		ids := utils.StrsTnums(idstrs)
		targetList := targets.FindByIds(ids)

		for _, t := range targetList {
			confStr += fmt.Sprintf(`
	server %s %s weight %s
`,
			t.TargetName,
			t.TargetService,
			t.TargetWeight)
		}
	}

	return confStr
}

func StartServ() {
	utils.ExecShell(haExcutor + " -f "+haConfPath+" -sf $(cat /var/run/haproxy.pid)")
}



func baseConfig(globalConfig models.GlobalConfig) string {
	return fmt.Sprintf(`
global
	chroot %s
	log %s
	maxconn %s
	nbproc %s
	user %s
	group %s
	daemon
	pidfile %s
defaults
	mode %s
	retries %s
	timeout connect %s
	timeout client %s
	timeout server %s
	timeout check %s

frontend default
mode http
option  httpclose
bind 0.0.0.0:5000
acl haproxy_stats   path_beg /haproxy
use_backend haproxy_stats if haproxy_stats

backend haproxy_stats
mode http
stats uri /haproxy
stats enable
stats refresh 60s
stats auth admin:admin
stats admin if TRUE
`,
globalConfig.GlobalChroot,
globalConfig.GlobalLog,
globalConfig.GlobalMaxconn,
globalConfig.GlobalNbproc,
globalConfig.GlobalUser,
globalConfig.GlobalGroup,
globalConfig.GlobalPidfile,
globalConfig.DefaultMod,
globalConfig.DefaultRetries,
globalConfig.DefaultConnectTimeout,
globalConfig.DefaultClientTimeout,
globalConfig.DefaultServerTimeout,
globalConfig.DefaultCheckTimeout)
}